package org.cyk.imgbed.test

import cn.hutool.http.HttpUtil
import cn.hutool.json.JSONUtil
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.lang.RuntimeException

@RestController
class UploadApi {

    @PostMapping("/upload")
    fun uploadImg(
        @RequestParam("file") multipartFile: MultipartFile
    ): String {
        //1.根据文件名生成指定的请求 url
        val originalFilename = multipartFile.originalFilename ?: throw RuntimeException("文件不存在")
        val targetURL = GiteeImgBed.createUploadFileUrl(originalFilename)
        println("获取到目标 url: $targetURL")
        //2.请求体封装
        val uploadBodyMap = GiteeImgBed.getUploadBodyMap(multipartFile.bytes)
        //3.通过 hutool 的 HttpUtil 工具发送 post 请求
        val JSONResult = HttpUtil.post(targetURL, uploadBodyMap)
        //4.解析 Json 响应
        val jsonObj = JSONUtil.parseObj(JSONResult)
        if(jsonObj == null || jsonObj.getObj("commit") == null) {
            return "请求失败"
        }
        //解析成功返回下载地址
        val content = JSONUtil.parseObj(jsonObj.getObj("content"))
        val result = content.getObj("download_url")
        return "成功, 下载地址: $result"
    }

}